package com.cc.exception;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import com.cc.base.ResponseResult;
import com.cc.enums.HttpsCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * @author zhanghaibin
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler(SaTokenException.class)
    public ResponseResult<String> handleException(SaTokenException e, HttpServletRequest request) {
        log.error("Sa-token鉴权异常---Url: {}", request.getRequestURI(), e);
        return ResponseResult.error(HttpsCode.NOT_LOGIN);
    }

    @ExceptionHandler(NotRoleException.class)
    public ResponseResult<String> handleException(NotRoleException e, HttpServletRequest request) {
        log.error("Sa-token鉴权异常---Url: {}", request.getRequestURI(), e);
        return ResponseResult.error(403, e.getMessage());
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResponseResult<String> handleException(NotPermissionException e, HttpServletRequest request) {
        log.error("Sa-token鉴权异常---Url: {}", request.getRequestURI(), e);
        return ResponseResult.error(403, e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseResult<String> businessException(BusinessException e, HttpServletRequest request) {
        log.error("业务异常异常--->{}", e.getMessage(), e);
        return ResponseResult.error(e.getCode(), e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResponseResult<String> businessException(Exception e, HttpServletRequest request) {
        log.error("服务器内部异常--->{}", e.getMessage(), e);
        return ResponseResult.error(HttpsCode.SYSTEM_ERROR);
    }


    @ExceptionHandler(NoResourceFoundException.class)
    public ResponseResult<String> noResourceFoundException(NoResourceFoundException e, HttpServletRequest request) {
        log.error("服务器内部异常--->{}", e.getMessage(), e);
        return ResponseResult.error(HttpsCode.RESOURCE_DOES_NOT_EXIST);
    }
}
